<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>科研项目管理</h2>
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate">
        发起项目
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchForm.title" placeholder="搜索项目名称" prefix-icon="el-icon-search" clearable
            @keyup.enter.native="handleSearch" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.status" placeholder="项目状态" clearable style="width: 100%">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 项目表格 -->
    <el-table v-loading="loading" :data="projectList" element-loading-text="加载中..." border fit highlight-current-row
      style="width: 100%">
      <el-table-column label="项目名称" min-width="250" align="left">
        <template slot-scope="{row}">
          <div class="project-name-cell">
            <div class="project-title" @click="handleDetail(row)">{{ row.title }}</div>
            <div class="project-desc">{{ row.description }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="项目时间" width="200" align="center">
        <template slot-scope="{row}">
          <div>{{ row.startDate | parseTime('{y}-{m}-{d}') }}</div>
          <div style="color: #909399; font-size: 12px;">至 {{ row.endDate | parseTime('{y}-{m}-{d}') }}</div>
        </template>
      </el-table-column>

      <el-table-column label="参与学生" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag type="info" size="small">{{ getStudentCount(row) }}人</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="节点数量" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag size="small">{{ getMilestoneCount(row) }}个</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="项目进度" width="150" align="center">
        <template slot-scope="{row}">
          <el-progress :percentage="getProgress(row)" :status="getProgressStatus(row)" :stroke-width="6"
            :show-text="false" />
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            {{ getProgress(row) }}%
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(parseInt(row.status))">
            {{ getStatusText(parseInt(row.status)) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleDetail(row)">
            查看
          </el-button>
          <el-button size="mini" @click="handleMilestones(row)">
            节点
          </el-button>
          <el-button size="mini" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)"
            v-if="parseInt(row.status) === 0 || parseInt(row.status) === 1">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.pageNo" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" />
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getTeacherProjects, deleteProject } from '@/api/research'

export default {
  name: 'ResearchProjects',
  filters: {
    parseTime
  },
  data() {
    return {
      loading: false,
      searchForm: {
        title: '',
        status: null
      },
      pagination: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      projectList: [],
      milestoneData: {} // 存储每个项目的节点数据
    }
  },
  created() {
    this.handleLoadProjects();
  },
  methods: {
    // 加载项目列表
    async handleLoadProjects() {
      this.loading = true
      try {
        // 合并分页参数和查询参数
        const params = {
          ...this.pagination,
          ...this.searchForm
        }
        const res = await getTeacherProjects(params)
        this.projectList = res.data.records
        this.total = res.data.total

        // 处理状态值，确保能正确显示
        this.projectList.forEach(project => {
          // 确保状态值为数字
          project.status = project.status || "0"
        })

      } catch (error) {
        console.error('获取教师项目列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNo = 1
      this.handleLoadProjects()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        title: '',
        status: null
      }
      this.handleSearch()
    },

    // 分页
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.handleLoadProjects()
    },

    handleCurrentChange(page) {
      this.pagination.pageNo = page
      this.handleLoadProjects()
    },

    // 操作方法
    handleCreate() {
      this.$router.push('/research/create')
    },

    handleDetail(project) {
      this.$router.push(`/research/detail/${project.id}`)
    },

    handleMilestones(project) {
      this.$router.push(`/research/milestones/${project.id}`)
    },

    handleEdit(project) {
      this.$router.push(`/research/create?id=${project.id}`)
    },

    async handleDelete(project) {
      try {
        await this.$confirm('确认删除该项目吗？删除后无法恢复。', '删除确认', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await deleteProject(project.id);
        this.$message.success('项目删除成功')
        this.handleLoadProjects()
      } catch (error) {
        console.error('删除项目失败:', error)
      }

    },

    // 工具方法
    getStatusType(status) {
      const types = { 0: 'info', 1: 'primary', 2: 'success' }
      return types[status] || 'info'
    },

    getStatusText(status) {
      const texts = { 0: '未开始', 1: '进行中', 2: '已完成' }
      return texts[status] || '未知'
    },

    getStudentCount(project) {
      // 使用API返回的项目成员数量
      return project.projectMemberNum || 0
    },

    getMilestoneCount(project) {
      // 使用API返回的项目节点数量
      return project.projectMilestoneNum || 0
    },

    getProgress(project) {
      const status = parseInt(project.status)

      // 如果项目已完成，直接返回100%
      if (status === 2) return 100

      // 如果项目未开始，返回0%
      if (status === 0) return 0

      // 根据时间计算进度
      try {
        const startDate = new Date(project.startDate)
        const endDate = new Date(project.endDate)
        const currentDate = new Date()

        // 检查日期有效性
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          return 0
        }

        // 如果当前时间在开始时间之前，返回0%
        if (currentDate < startDate) {
          return 0
        }

        // 如果当前时间在结束时间之后，根据状态返回进度
        if (currentDate >= endDate) {
          return status === 2 ? 100 : 95 // 已完成100%，否则95%（表示已到期但未完成）
        }

        // 计算时间进度
        const totalDuration = endDate.getTime() - startDate.getTime()
        const elapsedDuration = currentDate.getTime() - startDate.getTime()

        if (totalDuration <= 0) return 0

        const timeProgress = Math.round((elapsedDuration / totalDuration) * 100)

        // 确保进度在0-100之间
        return Math.max(0, Math.min(100, timeProgress))
      } catch (error) {
        console.error('计算项目进度失败:', error)
        // 如果时间计算失败，根据状态返回基础进度
        if (status === 0) return 0
        if (status === 1) return 50
        if (status === 2) return 100
        return 0
      }
    },

    getProgressStatus(project) {
      const status = parseInt(project.status)
      const progress = this.getProgress(project)

      // 已完成项目显示成功状态
      if (status === 2) return 'success'

      // 检查是否已过期
      try {
        const currentDate = new Date()
        const endDate = new Date(project.endDate)

        // 如果项目已过期但未完成，显示异常状态
        if (currentDate >= endDate && status !== 2) {
          return 'exception'
        }
      } catch (error) {
        console.error('检查项目过期状态失败:', error)
      }

      // 根据时间进度显示状态
      if (progress >= 80) return 'success'   // 进度良好
      if (progress >= 50) return ''          // 正常进度
      if (progress >= 20) return ''          // 正常进度
      return 'exception'                     // 进度较慢
    }
  }
}
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
  border: 1px solid #EBEEF5;
}

.project-name-cell {
  text-align: left;
}

.project-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  cursor: pointer;
  margin-bottom: 4px;
  line-height: 1.4;
}

.project-title:hover {
  color: #409EFF;
}

.project-desc {
  color: #909399;
  font-size: 13px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin: 0;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>